package com.hntx.joymusic.recordutils;

import android.media.MediaRecorder;

import java.io.File;

public class MediaRecordUtils {

    static MediaRecorder mRecorder;
    static File soundFile;
    private static String allPath;

    public static void startMediaRecord(String path) {
        try {
            // 创建保存录音的音频文件
            allPath = path + ".mp3";

            soundFile = new File(allPath);
            if (soundFile.exists()) {
                soundFile.delete();
            }
            soundFile.createNewFile();
            if (mRecorder == null) {
                mRecorder = new MediaRecorder();
                // 设置录音的声音来源
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//| MediaRecorder.AudioSource.DEFAULT
                // 设置录制的声音的输出格式（必须在设置声音编码格式之前设置）
                mRecorder.setOutputFormat(MediaRecorder
                        .OutputFormat.AMR_NB);
                // 设置声音编码的格式
                mRecorder.setAudioEncoder(MediaRecorder
                        .AudioEncoder.AMR_NB);
                mRecorder.setOutputFile(soundFile.getAbsolutePath());
                mRecorder.prepare();
                // 开始录音
                mRecorder.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String stopMediaRecord() {
        if (soundFile != null && soundFile.exists()) {
            // 停止录音
            try {
                if (mRecorder != null) {
                    mRecorder.stop();
                    // 释放资源
                    mRecorder.release();
                }
                mRecorder = null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
        return allPath;
    }

    public void destoryMediaRecord() {
        if (mRecorder != null) {
            // 停止录音
            mRecorder.stop();
            // 释放资源
            mRecorder.release();
            mRecorder = null;
        }
    }
}
